package com.eian.boot.security.handler;

import com.eian.boot.common.core.utils.SpringContextUtil;
import lombok.Data;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 获取所有Url配置
 */
@Data
public class AllUrlHandler implements InitializingBean {

    private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");

    private List<String> urls = new ArrayList<>();

    @Override
    public void afterPropertiesSet() {
        Set<String> set = new HashSet<>();
        RequestMappingHandlerMapping mapping = SpringContextUtil.getBean("requestMappingHandlerMapping", RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        map.keySet().forEach(info -> {
            if (info.getPathPatternsCondition() != null) {
                Objects.requireNonNull(info.getPathPatternsCondition().getPatterns())
                        .forEach(url -> {
                            Matcher matcher = PATTERN.matcher(url.getPatternString());
                            set.add(matcher.replaceAll("*"));
                        });
            }
        });
        urls.addAll(set);
    }
}
